package com.sinux.generality.basesupport.utils.tool;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.reflections.Reflections;
import org.reflections.scanners.MemberUsageScanner;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterNamesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;

public class FileTool {
	public static List<String> getFileList(String path, String extension){
		File file = new File(path);
		if(file.isFile()){
			throw new RuntimeException("the path is't a director");
		}
		File[] files = file.listFiles();
		List<String> filenames = new ArrayList<String>();
		for(int i = 0;i < files.length;i++){
			if(files[i].isFile()){
				filenames.add(files[i].getAbsolutePath());
			}
		}
		if(StringUtils.isNotBlank(extension)){
			return filenames.stream().filter(
						filename-> StringUtils.equals(extension, StringUtils.substringAfterLast(filename, "."))
					).collect(Collectors.toList()); 
		}
		return filenames;
	}
	
	public static Set<Method> compackageScanMethod(String packageName, Class<? extends Annotation> annoClass){
//		String path = FileTool.class.getResource("/"+packageName.replace(".", "/")).getPath();
//		File f = new File(path);
		Reflections f = new Reflections(packageName,
				Arrays.asList(
						new SubTypesScanner(false),
						new MethodParameterNamesScanner(),
						new MethodAnnotationsScanner(),
						new MemberUsageScanner(),
						new TypeAnnotationsScanner()
						));
		Set<Method> sets = f.getMethodsAnnotatedWith(annoClass);
		return sets;
	}
	
	public static Set<Class<?>> compackageScanType(String packageName, Class<? extends Annotation> annoClass){
//		String path = FileTool.class.getResource("/"+packageName.replace(".", "/")).getPath();
//		File f = new File(path);
		Reflections f = new Reflections(packageName);
		Set<Class<?>> sets = f.getTypesAnnotatedWith(annoClass);
		return sets;
	}
}
